import router from "@/router";
import axios from "axios";
import { message } from "ant-design-vue";
import { useAuthorizationStore } from "@/stores/authorization";
import { useUserStore } from "@/stores/user";
//引入nprogress进度条
import nprogress from "nprogress";
//引入nprogress样式
import "nprogress/nprogress.css";

const userStore = useUserStore();
const authorizationStore = useAuthorizationStore();
const request = axios.create({
  baseURL: "/api",
  timeout: 60000,
  headers: {
    // 设置后端需要的传参类型
    "X-Requested-With": "XMLHttpRequest",
  },
});

request.interceptors.request.use(
  (config) => {
    let authorization = authorizationStore.authorization;
    if (authorization) {
      config.headers["authorization"] = authorization; // 设置请求头
    }
    //进度条开始动
    nprogress.start();

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// request 拦截器
request.interceptors.response.use(
  function (response) {
    const res = response.data;
    const code = res.code;
    if (code !== 200) {
      message.error(res.message);
    }
    if (code === 403) {
      userStore.removeUser();
      authorizationStore.removeAuthorization();
      router.push("/login");
    }
    if (code === 1036) {
      router.push("/personal");
    }
    if (code === 1030) {
      userStore.removeUser();
      authorizationStore.removeAuthorization();
      router.push("/login");
    }

    //进度条结束
    nprogress.done();
    return res;
  },
  function (error) {
    console.log(error);
    let code = error.code;
    let message = error.message;
    //网络超时异常处理
    if (
      code === "ECONNABORTED" ||
      message === "timeout of 10000ms exceeded" ||
      message.includes("timeout")
    ) {
      message.error("请求超时，请检查网络");
    }
    return Promise.resolve(error);
  }
);

export default request;
